# -*- coding: utf-8 -*-
import wsgiref.handlers

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from BeautifulSoup import BeautifulSoup
from appengine_utilities import sessions
import xmw
from xmw.db import ds
import simplejson
import logging
from xmw.db import user_mgr

class MainPage(xmw.RequestHandler):
    def get(self):
        self.sess = sessions.Session()
        self.cookie_sess = sessions.Session(writer="cookie")    
        session_user =None
        if self.sess.has_key("user"):
            session_user=self.sess["user"]
        """ 
        else:
            (q_search_key_word,e) = self.get_key_from_GET('q_search_key_word')
            if q_search_key_word is not None:
                q_search_key_word  =q_search_key_word.strip().decode('utf-8')
                q_search_key_word =self.xmw_decoding(q_search_key_word)
                logging.log( logging.INFO, "q_search_key_word:%s"% q_search_key_word)
                self.sess['login_action']=ds.Login_Action(action="/search",params="q="+q_search_key_word)
                self.sess['login_action'].put()
        """
        
        #logging.log( logging.INFO, "self.sess['login_action']%s"% str(self.sess['login_action']))
        #logging.log( logging.INFO, "self.sess['user']%s"% str(self.sess['user']))
        #self.response.out.write("application/json; charset=utf-8")
        #self.response.out.write("""{"ok":true}""")
        #template_values={"is_registered":"true"}
        #self.render_template(template_values, "../html/j/is_registered.html")
        
        
        (title,e) = self.get_key_from_GET('title')
        if title is not None:
            title  =title.strip().decode('utf-8')
            title   =self.xmw_decoding(title)
            
        (url,e) = self.get_key_from_GET('url')
        if url is not None:
            url  =url.strip().decode('utf-8')
            url =self.xmw_decoding(url)
            logging.log( logging.INFO, "url:%s"% url)
        
        (seq,e) = self.get_key_from_GET('seq')
        if seq is not None:
            seq  =seq.strip().decode('utf-8')
            #seq =self.xmw_decoding(url)
            logging.log( logging.INFO, "seq:%s"% seq)  
            
        
        template_values ={"session_user":session_user,
                          "title":title,
                          "url":url,
                          "seq":seq,
                          }
        
        (sub_ack,e) = self.get_key_from_GET('sub_ack')
        if sub_ack is  None:
            #1.user should not sub the same url more than once
            #2.if the url already subed by other user,should fill the req's thread
            #info directly.
            
            #first check if the user has already sub the same thread
            if session_user is not None:
                sub_req=ds.Sub_Req().all()
                sub_req.filter('url =',url)
                sub_req.filter('user_id =',session_user.user_id)
                sub_req.filter('status !=', ds.Sub_Req_Status.DELETE)
                sub=sub_req.get()
                if sub is not None:
                    template_values["already_sub"]=True
                    
            self.render_template(template_values, "../html/j/subscribe/sub.html")
            return
        
        if sub_ack is not None:
            sub_ack  =seq.strip().decode('utf-8')
            #seq =self.xmw_decoding(url)
            logging.log( logging.INFO, "sub_ack:%s"% sub_ack) 
            
            (watch,e) = self.get_key_from_GET('watch')
            #0 or 1
            watch=watch.strip().decode('utf-8')
            watch=int(watch)
            
            sub_req=ds.Sub_Req()
            sub_req.user_id =session_user.user_id
            sub_req.title   =title.decode('utf-8')
            sub_req.url     =url
            sub_req.created =xmw.get_cn_now_time()
            sub_req.option=watch
            #second,check if the thread already in db by url.
            #if,fill the empty sub_req field by info from thread in db
            
            thread_q=xmw.Thread.all()
            thread_q.filter('lst_page_url  =',url)
            thread=thread_q.get()
            if thread is not None:
                sub_req.thread_id=thread.thread_id
                sub_req.status = ds.Sub_Req_Status.IN_TRACE
                sub_req.title=thread.title
            sub_req.save()
            self.render_template(template_values, "../html/j/subscribe/sub_ack.html")
            return
        #self.response.out
        
        return
    
def main():
    application = webapp.WSGIApplication(
                                       [('/j/subscribe/sub', MainPage),
                                        ],
                                       debug=True)
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()